import { http } from '@/utils/request'

// 认证相关接口

// 用户注册数据
export interface RegisterData {
  login: string  // 用户名/手机号/邮箱
  password: string
  nickname?: string
}

// 登录数据
export interface LoginData {
  login: string
  password: string
  device_info?: any
}

// 用户信息
export interface UserInfo {
  id: number
  username?: string
  phone?: string
  email?: string
  nickname: string
  avatar?: string
  master_key_hint?: string
  status: number
  last_login_at?: string
  created_at: string
  updated_at: string
}

// 登录响应
export interface LoginResponse {
  user: UserInfo
  token: string
}

// 第三方登录数据
export interface OAuthLoginData {
  code: string
  platform?: string
  device_info?: any
}

// 绑定数据
export interface BindOAuthData {
  platform: string
  code: string
}

// OAuth绑定信息
export interface OAuthBinding {
  platform: string
  nickname?: string
  avatar?: string
  created_at: string
}

/**
 * 用户注册
 */
export const register = (data: RegisterData) => {
  return http.post<{ user: UserInfo }>('/auth/register', data, {
    loading: true,
    loadingText: '注册中...'
  })
}

/**
 * 用户登录
 */
export const login = (data: LoginData) => {
  return http.post<LoginResponse>('/auth/login', data, {
    loading: true,
    loadingText: '登录中...'
  })
}

/**
 * 微信登录
 */
export const wechatLogin = (data: OAuthLoginData) => {
  return http.post<LoginResponse>('/auth/wechat-login', data, {
    loading: true,
    loadingText: '微信登录中...'
  })
}

/**
 * 支付宝登录
 */
export const alipayLogin = (data: OAuthLoginData) => {
  return http.post<LoginResponse>('/auth/alipay-login', {
    auth_code: data.code,
    device_info: data.device_info
  }, {
    loading: true,
    loadingText: '支付宝登录中...'
  })
}

/**
 * 抖音登录
 */
export const douyinLogin = (data: OAuthLoginData) => {
  return http.post<LoginResponse>('/auth/douyin-login', data, {
    loading: true,
    loadingText: '抖音登录中...'
  })
}

/**
 * 绑定第三方账号
 */
export const bindOAuth = (data: BindOAuthData) => {
  return http.post('/auth/bind', data, {
    loading: true,
    loadingText: '绑定中...'
  })
}

/**
 * 解绑第三方账号
 */
export const unbindOAuth = (platform: string) => {
  return http.delete('/auth/unbind', {
    data: { platform },
    loading: true,
    loadingText: '解绑中...'
  })
}

/**
 * 获取绑定列表
 */
export const getBindings = () => {
  return http.get<OAuthBinding[]>('/auth/bindings')
}

/**
 * 刷新Token
 */
export const refreshToken = (token: string) => {
  return http.post<{ token: string }>('/auth/refresh-token', { token })
}

/**
 * 退出登录
 */
export const logout = () => {
  return http.post('/auth/logout')
}